package controllers;

import play.*;
import play.i18n.Lang;
import play.i18n.Messages;
import play.mvc.*;

import java.util.*;
import java.io.*;

import com.google.gson.JsonObject;

import models.*;

public class Utility extends Controller {

    public static void index() {
    	
        render();
    }
    
    public static void upload(File file, String type, String t) throws Exception {
    	
    	if(file != null)
    	{
    		String filename = t + "_" + file.getName();
    		saveFile(filename, file);
    	}
    	
    	long time = System.currentTimeMillis();
    	
        render(time);
    }
    
    private static void saveFile(String fileName, File file) throws Exception{
    	String filePath = Play.tmpDir.getAbsoluteFile() + "/uploads/" + fileName;
    	
    	File fileUpload = new File(filePath);
    	
    	InputStream oInStream = null;
    	OutputStream oOutStream = null;
    	BufferedInputStream oBuffInputStream = null;
    	
    	// Transfer bytes from in to out
        byte[] oBytes = new byte[1024];
        int nLength;
    	
        if(!fileUpload.exists()){
        	fileUpload.createNewFile();
		}
        
        oOutStream = new FileOutputStream(fileUpload, true);
        
        oInStream = new FileInputStream(file);
        oBuffInputStream = new BufferedInputStream( oInStream );
        while ((nLength = oBuffInputStream.read(oBytes)) > 0) 
        {
            oOutStream.write(oBytes, 0, nLength);
        }
        
        oInStream.close();
        oOutStream.close();
    }
    
    public static void finishUpload(String t) throws Exception {
    	String tmpPath = Play.tmpDir.getAbsoluteFile() + "/uploads";
    	
    	JsonObject json = new JsonObject();
    	
    	try{
	    	File fileCsv = new File(tmpPath + "/" + t + "_csv.zip");
	    	File fileImage = new File(tmpPath + "/" + t + "_csv.zip");
	    	
	    	if(!fileCsv.exists()) fileCsv = null;
	    	if(!fileImage.exists()) fileCsv = null;
	    	
	    	json.addProperty("status", "success");
	    	
	    	// Call job
    	}
    	catch(Exception ex)
    	{
    		json.addProperty("status", "failure");
    	}
    	
		renderText(json.toString());
    }
}